package com.xm9m.web.service.controller;

import com.salesmanager.core.business.app.model.AndroidChannel;
import com.salesmanager.core.business.app.service.AppChannelService;
import com.salesmanager.web.utils.ImageFilePathUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by Liutong on 4/29/16.
 */
@Controller
public class AppDownloadController extends AbstractRestApiController {

    @Resource
    private AppChannelService appChannelService;

    @RequestMapping("/page/mm.app.download/{channelCode}")
    public String gotoDownloadUrl(@PathVariable("channelCode") String channelCode,
                                HttpServletRequest request) throws Exception{
        AndroidChannel androidChannel = appChannelService.getByChannelCode(channelCode);

        String apkUrl = null;

        //解析UA
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));

        //IOS 设备
        if (userAgent.getOperatingSystem().getName().toLowerCase().contains("iPad") || userAgent.getOperatingSystem().getName().toLowerCase().contains("iphone")){
            return "redirect:https://appsto.re/cn/IV3W-.i";
        } else {
            if (androidChannel != null){
                apkUrl = ImageFilePathUtils.buildChannelApkFilePath(androidChannel.getChannelCode(), androidChannel.getFileName(), request);
            }

            if (apkUrl != null){
                return "redirect:"+apkUrl;
            }
        }


        return "redirect:http://m.xm9m.com";
    }
}
